<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="selections.length == 0"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"> </el-table-column>

        <el-table-column
          v-for="item in tableColumns"
          :key="item.key"
          align="center"
          :label="item.title"
          :prop="item.key"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="220px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getCustomerCardList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        size="small"
        style="width: 95%; padding: 0 30px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡号" prop="card">
              <el-select
                v-model="form.card"
                placeholder="卡号"
                v-if="dialogType == 'new'"
                @change="onChange"
                clearable
              >
                <el-option
                  v-for="item in cards"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.code }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.money
                  }}</span>
                </el-option>
              </el-select>
              <el-input
                v-model="form.card_code"
                placeholder=""
                v-else
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="money">
              <el-input v-model="form.money" placeholder="金额" disabled>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customer">
              <el-select v-model="form.customer" placeholder="客户名称">
                <el-option
                  v-for="item in customers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售方式" prop="sale_class">
              <el-select v-model="form.sale_class" placeholder="销售方式">
                <el-option
                  v-for="item in classes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.sale_class===1">
          <el-col :span="12">
            <el-form-item label="收款账号" prop="account">
              <el-select v-model="form.account" placeholder="收款账号">
                <el-option
                  v-for="item in accounts"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实售金额" prop="actual_money">
              <el-input
                v-model="form.actual_money"
                placeholder="实售金额"
                :disabled="form.sale_class != 1"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="String"
                v-model="form.remark"
                placeholder="备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                disabled
                :active-value="1"
                active-text="已消费"
                :inactive-value="0"
                inactive-text="未消费"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="消费单号" prop="receipt_order_code">
              <el-input
                type="String"
                v-model="form.receipt_order_code"
                placeholder="消费单号"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消费时间" prop="receipt_time">
              <el-input
                type="String"
                v-model="form.receipt_time"
                placeholder="消费时间"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="default" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave(false)"
          >保存</el-button
        >
        <el-button type="success" size="small" @click="HandleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { pickerOptions } from "@/utils/const";
import {
  getCardList,
  getCustomerCards,
  addCustomerCard,
  updateCustomerCard,
  delCustomerCard,
  delCustomerCards,
} from "@/api/cards";

import { getCustomerList } from "@/api/base";
import { getAccountList } from "@/api/finance";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  customer: null,
  card: null,
  account: null,
  card_money: null,
  sale_class: null,
  actual_money: null,
  status: 0,
  remark: null,
  user: null,
};

export default {
  name: "CustomerCard",
  data() {
    // const checkMoney = (rule, value, callback) => {
    //   if (value == null || value.length === 0) {
    //     return callback(new Error("金额不能为空"));
    //   }
    //   if (isNaN(value)) {
    //     callback(new Error("请输入数字值"));
    //   } else {
    //     callback();
    //   }
    // };

    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        card: [{ required: true, message: "请选择优惠卡", trigger: "blur" }],
        customer: [{ required: true, message: "请选择客户", trigger: "blur" }],
      },

      title: "客户优惠卡",
      datas: [],
      customers: [],
      cards: [],
      accounts: [],
      selections: [],

      dialogVisible: false,
      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        status: null,
        name: undefined,
        search_date: "",
      },

      tableColumns: [
        {
          key: "code",
          title: "编号",
          width: "140",
        },
        {
          key: "customer_name",
          title: "客户名称",
          width: "140",
        },
        {
          key: "card_code",
          title: "卡号",
          width: "140",
        },

        {
          key: "sale_class_name",
          title: "销售方式",
        },
        {
          key: "card_money",
          title: "面值",
        },

        {
          key: "actual_money",
          title: "实售金额",
        },
        {
          key: "status_name",
          title: "状态",
        },
        {
          key: "receipt_order_code",
          title: "销售单号",
        },
        {
          key: "receipt_time",
          title: "消费时间",
        },
      ],

      pickerOptions,
      classes: [
        { id: 0, name: "赠送" },
        { id: 1, name: "销售" },
        { id: 2, name: "顶账" },
      ],
      stats: [
        { id: 0, name: "未消费" },
        { id: 1, name: "已消费" },
      ],
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCustomerCardList();
    this.getCustomerList();
    this.getCardList();
    this.getAccountList();
  },
  methods: {
    getCustomerCardList() {
      this.listLoading = true;
      getCustomerCards(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.datas = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    onChange(val){

      const index = this.cards.findIndex((v) => {
        return v.id === val;
      });
      this.form.money = null;
      if (index == -1) return;
      
      this.form.money = this.cards[index].money;
    },

    getCustomerList() {
      getCustomerList().then((res) => {
        this.customers = res;
      });
    },

    getCardList() {
      getCardList().then((res) => {
        this.cards = res;
      });
    },

    getAccountList() {
      getAccountList().then((res) => {
        this.accounts = res;
        for (let obj of this.accounts) {
          if (obj.default === 1) {

            defaultForm.account = obj.id;
          }
        }
      });
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "money" || column.property == "actual_money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },

    dataFormatter(row, column, cellValue, index) {
      if (column.property === "money" || column.property === "actual_money") {
        return cellValue && cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getCustomerCardList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCustomerCard(row.id);

          this.getCustomerCardList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("取消删除!");
        });
    },

    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delCustomerCards(sel_ids);

          this.getCustomerCardList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    // 保存操作
    async HandleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateCustomerCard(this.form);
        } else {
          this.form.user = this.uid;
          res = await addCustomerCard(this.form);
        }

        this.getCustomerCardList();
        this.getCardList();

        const { customer_name, card_code, money } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>客户名称: ${customer_name}</div>
              <div>客户名称: ${card_code}</div>
              <div>卡面值: ${money}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>